

######################################

## loop over possible combinations:
# 1st loop: variable used for ranking (ti or ti_posttax)
# 2nd loop: top fractiles
# 3rd loop: tax years

#################################
# 1st loop: over ranking variable
for(i in seq_along(rank_quos)) {

  # ranking variable
  rank_var <- rank_quos[[i]]
  
  # storage
  results <- list()
  
  #############################
  # 2nd loop over top shares
  for(j in seq_along(ts_vec)) {
    
    # top share
    ts <- ts_vec[j]
    
    # message
    message <- paste('Inner loop - Top share:', ts*100, 'percent')
    print(message)
      
      
    print('/---------- Top share calculations begin ---------/')
      
    ########################
    # 3rd loop over years
    tbl <- furrr::future_map_dfr(yy, table_top_share, .progress = T)
      
    # sequential
    #tbl <- purrr::map_dfr(yy, table_top_share)
      
    # 3rd loop ends
    ########################
      
    print('/---------- Top share calculations end -----------/')
      
    # include percentile 
    tbl <- tbl %>%
      mutate(ts = ts)
    
    # save results
    results[[j]] <- tbl
    
    # remove
    rm(tbl)

  }
  
  # 2nd loop ends
  ###############################
  
  # from list to dataframe
  results <- map_dfr(results, function(x){x})
  
  # ranking variable as string
  rank_str <- paste(rank_var)[2]
  
  # add ranking variable
  results <- results %>%
    mutate(rankvar = rank_str)
  
  # sample dummy
  results <- results %>%
    mutate(sample = which_sample)
  
  
  ## save output
  
  # migrant dummy string
  migrant_dummy_string <- paste(migrant_dummy_name)[2]
  
  # file name
  prefix <-
    paste('output/ts_',
          migrant_dummy_string,
          "_",
          sep = "")
  
  # age stub
  file_name <- paste(prefix, age_limit, 'plus', sep = "")
  
  # sample stub
  file_name <- paste(file_name, which_sample, sep = "_")
  
  
  # if not ranked on TI, change file name
  if (!rank_str == 'ti') {
    file_name <- paste(file_name, '_rank_', rank_str, '.csv', sep = "")
  } else {
    file_name <- paste(file_name, '.csv', sep = "")
  }
  
  
  # # # #
  
  # sort
  results <- results %>%
    arrange(group, desc(ts), tax_year)
  
  
  # write csv
  write_csv(results, path = file_name)
  
  # remove
  rm(results)
  
  
}  
# 3rd loop ends
##########################
  
  

